#-*- encoding:utf8 -*-

from django import http
from django.core.urlresolvers import reverse

from django.shortcuts import render
from tools import tools
from accounts import models as accounts_models
import json

def page(request,role):
    # 修改用户的当前角色
    request.user.group = int(role)
    request.user.save(update_fields=[u'group'])
    result = [{u'url':reverse('base.views.grid',args=[obj.object.id]),u'name':obj.object.text} for obj in request.user.get_objects_by_group()]

    return http.HttpResponse(json.dumps(result),content_type=u"application/json")

def __import_model(user,pk):
    path = user.get_objects_by_group().get(object__pk=pk).object.path
    role_name = user.groups.get(pk=user.group).name
    return tools.Import.import_model(path,role_name,user.username)

def grid(request,role_pk,pk):
    request.user.group = role_pk
    request.user.save(update_fields=['group'])
    model = __import_model(request.user,pk)
    template = model.school_get_template(request)
    context = model.school_get_context(request,pk)
    context[u'role_id'] = role_pk
    context[u'object_id'] = pk
    return http.HttpResponse(template.render(context))

def datas(request,role_pk,pk):
    request.user.group = role_pk
    request.user.save(update_fields=['group'])
    model = __import_model(request.user,pk)
    records = model.school_datas(request)
    return http.HttpResponse(json.dumps(records),content_type=u"application/json")

def ajaxtree(request):
    path = request.GET.get(u'model')
    field_name = request.GET.get(u'field')
    parent = request.GET.get(u'parent')
    level = request.GET.get(u'level')
    role_name = request.user.groups.get(pk=request.user.group).name
    model = tools.Import.import_model(path,role_name,request.user.username)
    field = model._meta.get_field(field_name)
    try:
        tree_method = getattr(model,u'ajax_tree_filter_%s'%field_name)
        result = tree_method(request,parent,level)
    except:
        result = field.rel.to.school_ajax_tree_items(request,parent,level)
    return http.HttpResponse(json.dumps(result),content_type=u"application/json")